<?php

// Error if we don't have a Project ID and Crudset ID
//Incluce DB connect 
include_once "quickcrud_connect.php";
//include_once "commonctls.php";
include_once "CF_mysql_com.php";
//include_once "CF_all_com.php";

include_once "qc_functions.php";

if (empty($_REQUEST['crudset_id']) OR empty($_REQUEST['project_id']) ){

        $result = "First select Project and CRUDset";
		
		print $result;
		
        exit;
}

	$project_id = $_REQUEST['project_id'];
	$crudset_id = $_REQUEST['crudset_id'];

	$showform = false;
	
if (!empty($_REQUEST['newname'])){
	$newname = $_REQUEST['newname'];
	$newname = trim($newname);	
	$exists_id = lookup_value('crudset_id','crudsets',"cs_name = '$newname' AND project_id = $project_id");
		if(!empty($exists_id)){
			$redundant = true;
			$showform = true;
		}
		else{
			$redundant = false;
		}
	
	}
else{
		$showform = true;
	}

// show form if new crudset name has not been specified	
if ($showform){

	if($redundant){
		echo "<p>The name $newname is already used in this project.  Please choose another <p>";
	}
	echo "<p>Please select a unique name for the CRUD set.  Include no spaces, and use only alphanueric characters (dashes, underscores ok).</p>";
		
	
	$txt_select_table = "<form name='select_table' action='copy_crudset.php' method='get'>\n";
    $txt_select_table .= "<p>Enter new name for CRUDset</p>\n <input type='text' name='newname' \>\n";
    $txt_select_table .= "<input type='hidden' name='project_id' value='$project_id' \>\n";
	$txt_select_table .= "<input type='hidden' name='crudset_id' value='$crudset_id' \><input type='submit' value='go'>\n";
    echo $txt_select_table;

	exit;
}

// create new crudset with info from old one
do_query("INSERT INTO crudsets (cs_name, paging, sorting, filter, main_table, project_id, query) 
SELECT '$newname', paging, sorting, filter, main_table, project_id, query FROM crudsets WHERE crudset_id = $crudset_id");
$new_set_id = get_max_value ('crudset_id', 'crudsets', '1');

// copy crudcols
$qry_copycols = "INSERT INTO crudcols (crudset_id, variable_id, is_key, shown_in_list, edit_in_list, edit_type, filter,
is_sort, header_name, is_add, list_query, list_keycol, list_showcol, size, rows)
SELECT $new_set_id, variable_id, is_key, shown_in_list, edit_in_list, edit_type, filter,
is_sort, header_name, is_add, list_query, list_keycol, list_showcol, size, rows
FROM crudcols WHERE crudset_id = $crudset_id";
do_query($qry_copycols );

// print result

print "<html>
<head>Copied Set</head>
</head>
<body onload=\"parent.frames['frame_menu'].location.reload();\">

<p>
Added new Crudset $newname
</p>
</body>
</html>";
?>